<?php
/**
 * 访问基础类
 *
 * @author Mo yi <root@imoi.cn>
 * @link   http://www.imoi.cn
 * @copyright Copyright &copy; 2010-2012 DuoLam Software LLC
 * @license http://www.imoi.cn/license/
 * @version $Id: dpAccess.php 2799 2012-04-04 09:31:13Z Mo.yi $
 * @package base
 * @since 1.0
 */

class dpAccess extends dpComponent
{
	protected $_controller;

	public $view;

	public $theme = false;

	public $layout = false;

	/**
	 * 构造方法，设置配置，执行action的__before方法，用于执行action前的一些操作
	 * 
	 */
	public function __construct()
	{
		$this->setConfig(D::$config);
	}

	/**
	 * action执行方法
	 */
	public function run()
	{
		$this->init();
		$actionID = $this->getAction();
		$before   = '_before' . $actionID;
		$action   = 'action'  . $actionID;
		$after    = '_after'  . $actionID;
		define('M', $this->getModule());
		define('C', $this->getControl());
		define('A', $this->getAction());
		method_exists($this, 'rules') && D::app()->rule()->run($this->rules(), $this); 
		method_exists($this, $before) && $this->$before();
		call_user_func_array(array($this,$action), $this->setActionParams($this, $action));
		method_exists($this, $after)  && $this->$after();
	}

	private function _classInfo($clsname, $methods = null)
	{
		$params = array();
	    $reflection = new ReflectionClass($clsname);
	    $aMethods = $reflection->getMethods();
	    foreach($aMethods as $param){
	        $name = $param->name;
	        $args = array();
	        if($methods){
	            if(strtolower($name) !== strtolower($methods))
	                continue;
	        }
	        foreach ($param->getParameters() as $n) {
	        	$params[$n->name] = '';
	        }
	        return $params;
	    }
	}

	public function setActionParams($clsname, $method)
	{
		$params = $this->_classInfo($clsname, $method);
		if (!empty($params)) {
			foreach($params as $n => $v) {
				if (isset($_GET[$n])) $params[$n] = $_GET[$n];
			}
		}
		return $params;
	}

	/**
	 * 执行action初始化
	 */
	public function init(){}

	/**
	 * 找不到任何的动作的时候会执行该动作
	 */
	public function __action()
	{
		dpException::error_404('您访问的动作不存在，你可以重载__action()方法做些什么！');
	}

	/**
	 * 魔术方法
	 */
	public function __call($name,$params)
	{
		$this->__action();
	}

	/**
	 * 魔术方法
	 */
	public function __set($name,$value)
	{
		$this->$name = $value;
	}

	/**
	 * 魔术方法
	 */
	public function __get($name)
	{
		return $this->$name;
	}

	/**
	 * 获取当前控制器名称
	 */
	public function getControl()
	{
		return dpUrlConfig::getController();
	}

	/**
	 * 获取当前动作名称
	 */
	public function getAction()
	{
		return dpUrlConfig::getAction();
	}

	/**
	 * 获取当前模块名称
	 */
	public function getModule()
	{
		return dpUrlConfig::getModule();
	}

	/**
	 * 向视图注入变量
	 * @param string or array $var   变量名或者变量列表
	 * @param string or array $value 变量值
	 */
	public function assign($var, $value = '')
	{
		if(!is_object($this->view))
			$this->view = $this->getModule() ? new dpModuleRender : new dpViewRender;
		$this->view->assign($var, $value);
	}

	/**
	 * 渲染视图
	 * @param string  $viewFile 视图文件名
	 * @param array   $var      注入模板的变量
	 * @param boolean $return   是否返回模板内容
	 */
	public function render($file = '', $var = '', $return = false)
	{
		$this->setThemeLayout();
		$file = empty($file) ? $this->getAction() : $file;
		return $this->view->render($file, $var, $return);
	}

	/**
	 * 设置主题和布局
	 */
	public function setThemeLayout()
	{
		if ($this->theme === true)
			$this->view->isTheme = true;
		else if (!empty($this->theme)) {
			$this->view->isTheme = true;
			$this->view->setTheme($this->theme);
		}

		if (!empty($this->layout)) {
			$this->view->isLayout = true;
			$this->view->layout   = $this->layout;
		}
	}

	/**
     * 是否AJAX请求
     * @return boolean
     */
    public function isAjax()
    {
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
        	'xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])) {
                return true;
        }
        return false;
    }

	/**
     * Ajax方式返回数据到客户端
     * @param mixed  $data 要返回的数据
     * @param String $type AJAX返回数据格式
     * @return void
     */
    public function ajaxReturn($data, $type='json')
    {
        switch ($type) {
            case 'json' :
                header('Content-Type:application/json; charset=utf-8');
                exit(json_encode($data));
            case 'xml'  :
                header('Content-Type:text/xml; charset=utf-8');
                exit(xml_encode($data)); 
            case 'text' :
                header('Content-Type:text/html; charset=utf-8');
                exit($data);
        }
    }

}